package com.yc.login;

import com.yc.login.bean.LoginProperteis;
import com.yc.login.web.LoginInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;

@AutoConfiguration
@ComponentScan("com.yc.login")
@ConditionalOnProperty(prefix = "login", name = "enable")
public class LoginAutoConfiguration implements WebMvcConfigurer {

    @Value("${spring.datasource.username}")
    String username;
    @Value("${spring.datasource.password}")
    String password;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.driver-class-name}")
    String driverClassName;

    @Bean
    @ConditionalOnMissingBean(type = "javax.sql.DataSource")
    public DataSource dataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setPassword(password);
        ds.setUsername(username);
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        return ds;
    }

    @Bean
    JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Resource
    LoginProperteis loginProperteis;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns(loginProperteis.getLoginScope());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/user/**")
                .addResourceLocations("file:F:\\_文件柜\\133\\组员(李四)\\yc-133" +
                        "\\login-starter\\src\\main\\resources\\static\\user/");
    }
}
